import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
// 请求超时处理响应
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(config => {
  if (store.state.user.token) {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
})

// response interceptor
// 响应拦截器
service.interceptors.response.use(res => {
  const { success, data, message } = res.data
  if (success) {
    return data
  } else {
    // element-ui 组件的弹窗提示
    Message.error(message)
    // 在promise运行的过程中,终止运行 使用原生对象promise.reject()
    return Promise.reject(new Error(message))
  }
}, err => {
  Message.error(err.message)
  return Promise.reject(err)
})

export default service
